<template>
  <a-upload v-bind="$attrs" v-on="$listeners" :action="actions" :headers="headers" with-credentials :on-success="handleSuccess" :before-upload="handleBeforeUpload">
    <slot></slot>
  </a-upload>
</template>

<script>
import { loadToken } from 'yz-help'
import { goLoginPage } from '../../../../permission'

export default {
  name: 'YzUpload',
  props: {
    action: {
      type: String,
      default: '',
      required: true
    },
    uploadImage: {
      type: Boolean,
      default: true
    },
    BeforeUpload: {
      type: Function,
      default: () => {}
    },
    OnSuccess: {
      type: Function,
      default: () => {}
    },
    //  是否是识别执照。默认不是
    isRecognize: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    actions () {
      if (this.action.startsWith('http') || this.action.startsWith('https')) {
        return this.action
      } else {
        return process.env.API_BASE_URL + this.action
      }
    },
    headers () {
      return { Authorization: 'Bearer ' + loadToken() }
    },
    /**
     * 上传成功的回调
     * @param response
     * @param file
     * @param fileList
     * 判断1402, 1473, 1579状态码
     * 调用传递过来的回调方法
     */
    handleSuccess (response, file, fileList) {
      // 1402 token过期
      // 1573 用户需要重新登录
      if (response.code === '1402' || response.code === '1573') {
        this.$message.error(response.message)
        return goLoginPage()
      }

      // 图片违规，提示违规原因
      //  1575 识别营业执照失败
      if (response.code === '1579' || response.code === '1575') {
        this.$message.error(response.message)
      }
      // 图片违规，提示违规原因
      // 如果是识别营业执照，不走下面判断，一般上传图片走下面判断
      if (!this.isRecognize && response.data && !response?.data?.url) {
        this.$message.error(response?.data?.name)
      }

      // 如果传了success回调，就执行该方法
      if (this.OnSuccess) {
        this.OnSuccess(response, file, fileList)
      }
      return true
    },
    /**
     * 上传前的处理
     * @param file
     * @private
     * 如果传了自定义的处理规则
     * 使用默认判断图片的规则
     */
    // eslint-disable-next-line vue/return-in-computed-property
    handleBeforeUpload (file) {
      if (this.BeforeUpload) {
        return this.BeforeUpload(file)
      } else {
        // 校验上传图片的默认规则
        if (this.uploadImage) {
          const isJPG = /\.(jpg|jpeg|png|bmp|BMP|JPG|PNG|JPEG|gif|GIF)$/.test(file.name)
          const isLt300k = file.size / 1024 < 300
          if (!isJPG) {
            this.$message.error('只可上传图片!')
            return isJPG
          }
          if (!isLt300k) {
            this.$message.error('上传图片大小不能超过300kb!')
            return isLt300k
          }
          return isJPG && isLt300k
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
